﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace SRB.Tg.Operate
{
    public class XMLUtiles
    {
        /// <summary>
        /// xml解析成实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml">xml文本</param>
        /// <param name="model">实体对象</param>
        /// <returns>带值实体对象</returns>
        public static T XmlToModel<T>(string xml, T model)
        {
            StringReader xmlReader = new StringReader(xml);
            XmlSerializer xmlSer = new XmlSerializer(typeof(T));
            return (T)xmlSer.Deserialize(xmlReader);
        }

        /// <summary>
        /// 实体解析成xml
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model">实体对象</param>
        /// <returns>xml文本</returns>
        public static string ModelToXml<T>(T model)
        {
            MemoryStream stream = new MemoryStream();
            XmlSerializer xmlSer = new XmlSerializer(typeof(T));
            xmlSer.Serialize(stream, model);
            stream.Position = 0;
            StreamReader sr = new StreamReader(stream);
            return sr.ReadToEnd();
        }
    }
}
